package com.zhu.storesmanager.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;

import com.zhu.storesmanager.SvStoreCompeteActivity;
import com.zhu.storesmanager.SvVisitTaskActivity;
import com.zhu.storesmanager.models.CompeteProductItem;
import com.zhu.storesmanager.models.DataItem;
import com.zhu.storesmanager.models.ModelItem;
import com.zhu.storesmanager.models.ProjectDataItem;
import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.network.HttpUtil;
import com.zhu.storesmanager.network.SyncUtil;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.security.DesUtil;

public class DatabaseUtil {

	private static final int REPORTEDSALES_COUMT_LIMIT = 300;
	//拜访类型
	public static final int TYPE_SHAPE = 0; //出样
	public static final int TYPE_BOOTH = 1; //展台
	public static final int TYPE_SALES = 2; //销量
	public static final int TYPE_POSM = 3; //POSM
	public static final int TYPE_COMPETE = 4; //竞品
	public static final int TYPE_PROMOTER = 5; //促销员
	public static final int TYPE_TASK = 6; //特殊任务
	public static final int[] VISIT_STATUS = {0, 0, 0, 0, 0, 0, 0}; //拜访状态标致位

	/**
	 * 从数据库获取促销员签入数据
	 */
	public static SyncModel.PromoterCheckRequest getPromoterCheckData(Context context){
		SyncModel.PromoterCheckRequest result = null;
		String where = StoresManagerSettings.SignInInfoColumns.SINGIN_TIME + ">0"; //查询数据库条件
		Cursor cursor = context.getContentResolver().query(StoresManagerSettings.SignInInfoColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null); //查询
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()){ //数据存在 则已经签到成功
			result = new SyncModel.PromoterCheckRequest(); 
			result.CheckInTime = new Date(cursor.getLong(cursor.getColumnIndexOrThrow(StoresManagerSettings.SignInInfoColumns.SINGIN_TIME)));
			result.CheckInLatitude = Double.parseDouble(cursor.getString(cursor.getColumnIndexOrThrow(StoresManagerSettings.SignInInfoColumns.SINGIN_LAT)));
			result.CheckInLongitude = Double.parseDouble(cursor.getString(cursor.getColumnIndexOrThrow(StoresManagerSettings.SignInInfoColumns.SINGIN_LNG)));
			result.MobileTime = new Date();
			result.WorkDate = new Date();
		}
		if(cursor != null){
			cursor.close();
			cursor = null;
		}
		return result;
	}

	
	/**
	 * 保存销量上报后的数据至本地
	 * @param context 上下文
	 * @param savelist 需要保存的数据集合
	 * @param reportTime 上报时间
	 */
	public static void saveReportSalesData(Context context, List<ModelItem> savelist, long reportTime){
		ContentValues values = new ContentValues();
		for(ModelItem item : savelist){
			values.clear(); //清空
			String where = StoresManagerSettings.ReportedSalesColumns.MODELNAME + "=\'" + item.mName +"\'";
			//查询该数据是否以存在数据库中
			long dbid = SyncUtil.getDatabaseId(context, StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION, where);
			values.put(StoresManagerSettings.ReportedSalesColumns.REPORTTIME, reportTime);
			values.put(StoresManagerSettings.ReportedSalesColumns.SALESNUM, item.mQuantity);
			values.put(StoresManagerSettings.ReportedSalesColumns.SALESPRICE, item.mPrice);
			if(dbid == -1){//不存在则插入数据
				values.put(StoresManagerSettings.ReportedSalesColumns.MODELNAME, item.mName);
				context.getContentResolver().insert(StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION, values);
			}else{
				context.getContentResolver().update(StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION, values, where, null);
			}
		}
		//更具上报日期删除超过限制的数据
		Cursor cursor = context.getContentResolver().query(StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION,
				SyncUtil.PROJECTION, null, null, StoresManagerSettings.ReportedSalesColumns.REPORTTIME + " ASC");
		int needDeleteCount = 0; //需要删除的数据数量
		try{
			int idIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.ReportedSalesColumns._ID);
			if(cursor != null && cursor.getCount() > REPORTEDSALES_COUMT_LIMIT && cursor.moveToFirst()){//如果数据超过显示数量 则进行删除
				needDeleteCount = cursor.getCount() - REPORTEDSALES_COUMT_LIMIT;
				String where = ""; //删除条件
				for(int i = 0; i < needDeleteCount; i++){ //遍历需要删除项数据
					if(where.length() == 0){
						where = SyncUtil.getQueryWhere(StoresManagerSettings.ReportedSalesColumns._ID, "" + cursor.getLong(idIndex));
					}else{
						where += " or " + SyncUtil.getQueryWhere(StoresManagerSettings.ReportedSalesColumns._ID, "" +cursor.getLong(idIndex));
					}
					cursor.moveToNext();
				}
				if(where.length() > 0){
					context.getContentResolver().delete(StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION, where, null);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			Log.e("saveReportSalesData delete error");
		}
	}

	/**
	 * 获取所有销量数据
	 */
	public static SyncModel.PromoterSalesRequest getPromoterSalesData(Context context, List<ModelItem> list){
		SyncModel.PromoterSalesRequest result = new SyncModel.PromoterSalesRequest();
		List<SyncModel.PromoterSalesReqModel> modelList = new ArrayList<SyncModel.PromoterSalesReqModel>();
		for(ModelItem item : list){
			SyncModel.PromoterSalesReqModel model = new SyncModel.PromoterSalesReqModel();
			model.Model = item.mName;
			model.Num = item.mQuantity;
			model.Amount = item.mPrice;
			modelList.add(model);
		}
		String listJson = HttpUtil.getPutPromoterSalesContent(modelList);
		String listJsonDes = DesUtil.des3EncodeECB2(HttpUtil.mDesKey, listJson);
		result.SalesDes = listJsonDes;
		return result;
	}

	/**
	 * 促销员特殊任务
	 */
	public static SyncModel.PromoterContentRequest getPromoterTaskData(Context context){
		Cursor cursor = context.getContentResolver().query(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, null,
				null, null, null);
		SyncModel.PromoterContentRequest result = null;
		try {
			//获取数据index
			final int storeIdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.STOREID);
            final int taskdesIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.TASK_DES);
            final int taskfdIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SpecialTaskColumns.TASK_FEEDBACK);
            while (cursor.moveToNext()) {
            	String storeId = cursor.getString(storeIdIndex);
            	    if(result == null){
            	    	result = new SyncModel.PromoterContentRequest();
            	    	result.Data = new SyncModel.PromoterContentReqData();
            	    	result.Data.Specials = new ArrayList<SyncModel.DataVisitContentSpecial>();
            	    }
			    	SyncModel.DataVisitContentSpecial specialA = new SyncModel.DataVisitContentSpecial();
			    	specialA.Title = cursor.getString(taskdesIndex);
			    	specialA.Value = cursor.getString(taskfdIndex);
			    	result.Data.Specials.add(specialA);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = null;
            Log.e("getPromoterTaskData error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        	return result;
        }
	}

	/**
	 * 保存竞品数据
	 * @param context 上下文
	 * @param dataList 数据集合
	 * @param storeId 门店ID
	 * @param type 数据类型
	 */
	public static void saveCompeteData(Context context, List<CompeteProductItem> dataList, String storeId, int type){
	    ContentValues values = new ContentValues();
	    for(CompeteProductItem item : dataList){
	        values.clear();
	        values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.STOREID, storeId);
	        values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_TYPE, type);
	        values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_BRANDID, item.mBrandId);
	        values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_BRANDNAME, item.mBrandName);
	        values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_PRICE, item.mPrice);
	        values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_MODELNAME, item.mModelName);
	        values.put(StoresManagerSettings.SAVED, 0);
	        if(type == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_PRICE){
	            values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_MODELID, item.mModelID);	            
	        }else {
	            if(type == SvStoreCompeteActivity.TYPE_COMPETE_CONTENT_ACTIVITY){
	                values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_SELLCOUNT, item.mSellcount);
	            }
	            values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_DATAIDS, item.mDataIDs);
	            values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_DATANAMES, item.mDataNames);
	            values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_OTHERS, item.mOther);
	            if(item.mPhoto != null){
	                values.put(StoresManagerSettings.SupervisorStoreCompeteColumns.COMPETE_PHOTO, getBitmapData(item.mPhoto));
	            }
	        }
	        context.getContentResolver().insert(StoresManagerSettings.SupervisorStoreCompeteColumns.CONTENT_URI_NO_NOTIFICATION, values);
	    }
	}

	 /**
     * 获取保存的图片数据
     */
    public static byte[] getBitmapData(Bitmap bitmap) {
        if(bitmap != null){
             int size = bitmap.getWidth() * bitmap.getHeight() * 4;
                ByteArrayOutputStream out = new ByteArrayOutputStream(size);
                try {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();
                    return out.toByteArray();
                } catch (IOException e) {
                    return null;
                }
        }
        return null;
    }

    /**
     * 从查询结果数据获取拜访项集合
     */
    public static List<ProjectDataItem> getProjectDataList(Cursor cursor){
    	List<ProjectDataItem> list = null;
    	try {
    		if(cursor == null || cursor.getCount() == 0){
    			return null;
    		}
			list = new ArrayList<ProjectDataItem>(); //数据集

			final int typeIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE);
            final int nameIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_NAME);
            final int saveIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_SAVE);
            final int showIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_SHOW);
            final int sequenceIndex = cursor.getColumnIndexOrThrow(StoresManagerSettings.DataProjectsColumns.ITEM_SEQUENCE);
            while (cursor.moveToNext()) {//遍历所有型号数据
            	ProjectDataItem item = new ProjectDataItem();
            	item.mName = cursor.getString(nameIndex);
            	item.isSave = cursor.getInt(saveIndex) == 1 ? true : false;
            	item.isShow = cursor.getInt(showIndex) == 1 ? true : false;
            	item.mId = cursor.getInt(sequenceIndex);
            	item.mType = cursor.getInt(typeIndex);
            	list.add(item);
            }
            //更新界面数据
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("updateDataItemFromCursor error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        		cursor = null;
        	}
        }
    	return list;
    }

    /**
     * 保存拜访状态
     * @param context 上下文
     * @param visitId 拜访ID
     * @param type 拜访类型 (TYPE_SHAPE)
     * @param value 保存状态值 1为填写完整  否则为0
     */
    public static void saveVisitStatus(Context context, int type, int visitId, int value){
    	ContentValues values = new ContentValues();
    	switch(type){
    		case TYPE_SHAPE:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_SHAPE, value);
    			break;
    		case TYPE_BOOTH:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_BOOTH, value);
        		break;
    		case TYPE_SALES:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_SALES, value);
        		break;
    		case TYPE_POSM:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_POSM, value);
        		break;
    		case TYPE_COMPETE:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_COMPETE, value);
        		break;
    		case TYPE_PROMOTER:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_PROMOTER, value);
        		break;
    		case TYPE_TASK:
    			values.put(StoresManagerSettings.VisitStatusColumns.STATUS_TASK, value);
        		break;
    	}
    	long dbid = SyncUtil.getDatabaseId(context, StoresManagerSettings.VisitStatusColumns.CONTENT_URI_NO_NOTIFICATION, 
				StoresManagerSettings.VisitStatusColumns.STATUS_VISITID + "=" + visitId); //检查数据是否存在
    	if(dbid == -1){
    		values.put(StoresManagerSettings.VisitStatusColumns.STATUS_VISITID, visitId);
    		context.getContentResolver().insert(StoresManagerSettings.VisitStatusColumns.CONTENT_URI_NO_NOTIFICATION, values);
    	}else{
    		context.getContentResolver().update(StoresManagerSettings.VisitStatusColumns.getContentUri(dbid, false), values, null, null);
    	}
    }

    /**
     * 检测是否可以结束拜访
     * @param context 上下文
     * @param visitId 拜访任务ID
     * @param storeId 门店ID
     * @return true 可以
     */
    public static boolean canEndVisit(Context context, int visitId, String storeId){
    	for(int i = 0; i < VISIT_STATUS.length; i++){
    		VISIT_STATUS[i] = 0;
    	}
    	boolean hadPromoter = false; //是否有促销员
    	String where = StoresManagerSettings.SupervisorStorePromoterColumns.STOREID + "=\'" + storeId +"\' AND " + 
        StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_LAST + "=0";
    	Cursor pcursor = context.getContentResolver().query(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, null,
    			where, null, null);
    	if(pcursor != null && pcursor.getCount() > 0){
    		hadPromoter = true;
    	}
    	if(pcursor != null){
    		pcursor.close();
    		pcursor = null;
    	}
    	boolean end = false;
    	where = StoresManagerSettings.VisitStatusColumns.STATUS_VISITID + "=" + visitId;
    	Cursor cursor = context.getContentResolver().query(StoresManagerSettings.VisitStatusColumns.CONTENT_URI_NO_NOTIFICATION,
    			null, where, null, null); //查询
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()){
			int shape = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_SHAPE));
			int booth = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_BOOTH));
			int sales = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_SALES));
			int posm = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_POSM));
			int compete = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_COMPETE));
			int promoter = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_PROMOTER));
			int task = cursor.getInt(cursor.getColumnIndexOrThrow(StoresManagerSettings.VisitStatusColumns.STATUS_TASK));
			Log.d(hadPromoter +"," + shape +"," + booth +"," + sales +"," + posm +","+compete +","+promoter +","+task);
			if(!hadPromoter){ //没有促销员信息则默认为1
				promoter = 1;
			}
			VISIT_STATUS[0] = shape; //出样
			VISIT_STATUS[1] = booth; //展台
			VISIT_STATUS[2] = sales; //销量
			VISIT_STATUS[3] = posm;  //POSM
			VISIT_STATUS[4] = compete; //竞品
			VISIT_STATUS[5] = promoter; //促销员
			VISIT_STATUS[6] = task; //特殊任务
			if(shape == 1 && booth == 1 && sales == 1 && posm == 1 && compete == 1 && promoter == 1 && task == 1){
				end = true;
			}
		}
		if(cursor != null){
			cursor.close();
			cursor = null;
		}
		return end;
    }

    /**
     * 检测是否有提醒数据
     * @return true 存在
     */
    public static boolean hasRemindData(Context context){
    	boolean hasData = false;
    	Cursor cursor = context.getContentResolver().query(StoresManagerSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION,
    			SyncUtil.PROJECTION, null, null, null); //查询
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()){
			hasData = true;
		}
		if(cursor != null){
			cursor.close();
			cursor = null;
		}
		return hasData;
    }

    /**
     * 检测是否结束拜访
     * @param context
     */
	public static boolean isEndVisit(Context context){
        Cursor cursor = null;
        boolean isCheckin = false;
        boolean isCheckout = false;
        try{
            String where = StoresManagerSettings.SupervisorVisitTaskColumns.STOREID + " = \'" + SvVisitTaskActivity.STARTCHECKID +
            		"\' OR "+ StoresManagerSettings.SupervisorVisitTaskColumns.STOREID + " = \'"+ SvVisitTaskActivity.STOPCHECKID+"\'";
            cursor = context.getContentResolver().query(StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI, null, where, null, null);
            int cidindex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.STOREID);
            int checkindex = cursor.getColumnIndexOrThrow(StoresManagerSettings.SupervisorVisitTaskColumns.CHECKIN_TIME);
            while (cursor.moveToNext()) {
                String tid = cursor.getString(cidindex);
                String checkintime = cursor.getString(checkindex);
                if(tid.equals(SvVisitTaskActivity.STARTCHECKID) && checkintime != null && checkintime.length() > 1){
                    isCheckin = true;
                }else if(tid.equals(SvVisitTaskActivity.STOPCHECKID) && checkintime != null && checkintime.length() > 1){
                    isCheckout = true;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
            if(!isCheckin || (isCheckin && isCheckout)){
                return true;
            }
            return false;
        }
    }
}
